package com.newlink.building.common_base.http.tools

import com.newlink.building.common_base.base.BaseApplication
import com.newlink.building.common_base.utils.Base_DeviceUtils
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

/**
 * @Author: Jake
 * @Date: 2024-08-13
 * @Description:
 */
class Base_CookieJar : CookieJar {
    private val cookieStore: MutableMap<String, MutableList<Cookie>> = mutableMapOf()

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        cookieStore[url.host] = cookies.toMutableList()
    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val cookies = cookieStore[url.host] ?: mutableListOf()

        // 在每次请求时可以动态添加或修改 Cookie
        val typeCookie = Cookie.Builder()
            .domain(url.host)
            .path("/")
            .name("AppType")
            .value("Android")
            .build()

        val versionCookie = Cookie.Builder()
            .domain(url.host)
            .path("/")
            .name("AppVersion")
            .value("${Base_DeviceUtils.getAppVersion(BaseApplication.context)}")
            .build()

        cookies.add(typeCookie)
        cookies.add(versionCookie)

        return cookies
    }
}